package com.jthinker.blog.web.controller.admin.post;

import com.alibaba.fastjson.JSON;
import com.jthinker.blog.bean.entity.Category;
import com.jthinker.blog.bean.entity.Post;
import com.jthinker.blog.bean.entity.User;
import com.jthinker.blog.bean.vo.Constant;
import com.jthinker.blog.bean.vo.UserWrapper;
import com.jthinker.blog.service.PostService;
import com.jthinker.blog.service.UserInfoService;
import com.jthinker.blog.web.controller.admin.common.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * User: Gang Chen
 * Date: 2015/7/4 21:57
 */
@Controller
@RequestMapping("/postMgr")
public class PostMgrController extends BaseController
{
    private static final Logger LOGGER = LoggerFactory.getLogger(PostMgrController.class);

    @Autowired
    private PostService postService;

    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping("/listView")
    public String listView()
    {
        return "post/postList";
    }

    @RequestMapping("/getListData")
    @ResponseBody
    public Map<String, Object> getListData(HttpServletRequest request)
    {
        String queryHql = "SELECT new Map(post.id as id,post.title as title,post.name as name,post.postDate as postDate,post.commentCount as commentCount,category.name as cname,user.nickname as nickname,user.id as uid)  FROM Post post,Category category,User user WHERE post.category.id=category.id and post.user.id=user.id";
        String countHql = "SELECT count(*) FROM Post post,Category category,User user WHERE post.category.id=category.id and post.user.id=user.id";
        return super.getListDataByHql(request, postService, countHql, queryHql);
    }

    @RequestMapping("/view")
    public ModelAndView view(Long id)
    {
        ModelAndView mv = new ModelAndView("post/postView");
        if (id != null)
        {
            Post post = postService.readDetail(id);
            mv.addObject("post", JSON.toJSONString(post));
        }
        return mv;
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Map<String, Object> saveOrUpdate(@Valid Post post, BindingResult result, HttpServletRequest request)
    {
        if (result.hasErrors())
        {
            return generateErrorMessage(result);
        }

        UserWrapper userWrapper = userInfoService.getCurrentUser(request);

        User user = new User();
        user.setId(userWrapper.getId());
        post.setUser(user);

        String excert = post.getExcerpt();

        if (StringUtils.isBlank(excert))
        {
            excert = getExcerpt(post.getContent());
            post.setExcerpt(excert);
        }

        String name = post.getName();
        if (StringUtils.isBlank(name))
        {
            try
            {
                name = URLEncoder.encode(post.getTitle(), Constant.DEFAULT_ENCODING);
            }
            catch (UnsupportedEncodingException e)
            {
                LOGGER.error("{}", e);
            }
            post.setName(name);
        }

        if (post.getCategory() == null || post.getCategory().getId() == null)
        {
            Category category = new Category();
            category.setId(Constant.DEFAULT_CATEGORY_ID);
            post.setCategory(category);
        }

        if (post.getId() != null)
        {
            Post old = postService.get(post.getId());
            post.setPostDate(old.getPostDate());
        }

        postService.merge(post);

        return getSuccessMessage("保存成功!");
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, Object> delete(Long id)
    {
        if (id == null)
        {
            return getErrorMessage("请选择行!");
        }

        postService.delete(id);
        return getSuccessMessage("删除成功!");
    }

    private String getExcerpt(String content)
    {
        return StringUtils
                .substring(content.replaceAll("<.*?>", "").replaceAll(" ", "").replaceAll("<.*?", ""), 0, Constant.DEFAULT_EXCERPT_LENGTH);
    }
}
